#include<iostream>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

char buffer[1024];
int main()//演示pipe通信的基本过程-匿名管道
{   
    int pipefd[2]={0};
    int ret=pipe(pipefd);
    if(ret<0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }
    pid_t id=fork();
    if(id<0)
    {
        cerr<<"fork error"<<endl;
        return 2;
    }
    else if(id==0)//子进程-读-0
    {
        close(pipefd[1]);
        while(1)
        {
            memset(buffer,0,sizeof(buffer));
            ssize_t num=read(pipefd[0],buffer,sizeof(buffer));
            if(num>0)
            {
                buffer[num]='\0';
                cout<<"buffer:"<<buffer<<endl;
            }
            else if(num==0)
            {
                cout<<"子进程退出"<<endl;
                break;
            }
            else{
                //do nothing
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    else{//父进程
        close(pipefd[0]);
        const char* msg="你好子进程，我是父进程, 这次发送的信息编号是:";
        int cnt=5;
        while(cnt--)
        {
            char sendbuffer[1024];
            memset(sendbuffer,0,sizeof(sendbuffer));
            sprintf(sendbuffer,"%s:%d\n",msg,cnt);
            write(pipefd[1],sendbuffer,strlen(sendbuffer));
        }
        close(pipefd[1]);
        cout<<"父进程写完了——————————————————"<<endl;
    }
    pid_t res=waitpid(id,nullptr,0);
    if(res>0)
    {
        cout<<"父进程等待成功"<<endl;
    }
    return 0;
}

